/**
 * 
 */

$(function(){
	
	//查询
	$("#btnSearch").click(function(){
		debugger
		var formSerialize = $("#form").serializeObject();
		var v = JSON.stringify(formSerialize);
		$("#v").val(encodeURIComponent(v));
		form.submit();
	});
	
    $("#advmentSelectId").autocomplete({
        source: global.rootPath + "/adv/place/queryList",
        minLength: 1,
        select: function( event, ui ) {
        	$("#advmentId").val(ui.item.id);
        	//alert(ui.item.value + "-" + ui.item.id);
//          log( ui.item ?
//            "Selected: " + ui.item.value + " aka " + ui.item.id :
//            "Nothing selected, input was " + this.value );
        }
      });
	
});

function add() {
	
	$.layer({
	    type: 2,
	    shade: [0],
	    fix: false,
	    title: '添加广告位',
	    maxmin: false,
	    iframe: {src : global.rootPath + "/adv/place/add?type=init"},
	    area: ['500px' , '500px'],
	    close: function(index){
	    }
	});
}

function addPlace() {
	var name = $("#advmentSelectId").val();
	var advmentId = $("#advmentId").val();
	var sortNo = $("#sortNo").val();
	var beginTime = $("#beginTime").val();
	var endTime = $("#endTime").val();
	
	if (null == name || "" == name) {
		layer.tips("广告名称不能为空", $("#advmentSelectId") , {guide: 3, time: 3,more:true});
		return false;
	}
	
	var imgUrl = $("#imgUrl").val();
	if (null == imgUrl || "" == imgUrl) {
		layer.tips("广告图标不能为空", $("#imgUrl") , {guide: 3, time: 3,more:true});
		return false;
	}
	if (null == advmentId || "" == advmentId) {
		layer.tips("请输入已上传的广告名称", $("#advmentSelectId") , {guide: 3, time: 3,more:true});
		return false;
	} else {
		if (isNaN(advmentId)) {
			layer.tips("请输入已上传的广告名称", $("#advmentSelectId") , {guide: 3, time: 3,more:true});
			return false;	
		}
	}
	
	if (null == beginTime || "" == beginTime) {
		layer.tips("请选择开始时间", $("#beginTime") , {guide: 3, time: 3,more:true});
		return false;
	}
	
	if (null == endTime || "" == endTime) {
		layer.tips("请选择结束时间", $("#endTime") , {guide: 3, time: 3,more:true});
		return false;
	}
	
	//ajax file upload
	$.ajaxFileUpload({
		url : global.rootPath + "/adv/place/add?type=add",
		fileElementId:"logoFile",
		dataType: 'json',
		
		data : {
			name : encodeURIComponent(name),
			advmentId : advmentId,
			sortNo : sortNo,
			beginTime :beginTime,
			endTime : endTime
		},
		success: function(data,status) {
			//parent.layer.msg(data.msg, 2);
			parent.location.reload();
			var index = parent.layer.getFrameIndex(window.name);
			parent.layer.close(index);
//			debugger
//			if (data.success) {
//				parent.layer.msg(data.msg, 2);
//				refresh();
//    			var index = parent.layer.getFrameIndex(window.name);
//    			parent.layer.close(index);
//    			
//			} else {
//            	//parent.layer.msg(data.msg, 2);
//			}
		},
		error:function(data,status,e) {
			parent.layer.msg(data.msg, 3);
		}
	});
	
}

function update(id) {
	
	$.layer({
	    type: 2,
	    shade: [0],
	    fix: false,
	    title: '修改广告位',
	    maxmin: false,
	    iframe: {src : global.rootPath + "/adv/place/update?type=init&id="+id},
	    area: ['500px' , '500px'],
	    close: function(index){
	    }
	});
}

function updatePlace() {
	var name = $("#name").val();
	var advmentId = $("#advmentId").val();
	var id = $("#id").val();
	var playTime = $("#playTime").val();
	
	var beginTime = $("#beginTime").val();
	var endTime = $("#endTime").val();
	
	if (null == name || "" == name) {
		layer.tips("广告名称不能为空", $("#name") , {guide: 3, time: 3,more:true});
		return false;
	}
	
	var imgUrl = $("#imgUrl").val();
	//if (null == imgUrl || "" == imgUrl) {
	//	layer.tips("分类图标不能为空", $("#imgUrl") , {guide: 3, time: 3,more:true});
	//	return false;
	//}
	
	if (null == advmentId || "" == advmentId) {
		layer.tips("请选择广告", $("#advmentId") , {guide: 3, time: 3,more:true});
		return false;
	} else {
		if (isNaN(advmentId)) {
			layer.tips("广告ID为有效数字", $("#advmentId") , {guide: 3, time: 3,more:true});
			return false;	
		}
	}
	
	if (null == beginTime || "" == beginTime) {
		layer.tips("请选择开始时间", $("#beginTime") , {guide: 3, time: 3,more:true});
		return false;
	}
	
	if (null == endTime || "" == endTime) {
		layer.tips("请选择结束时间", $("#endTime") , {guide: 3, time: 3,more:true});
		return false;
	}
	
	
	//ajax file upload
	$.ajaxFileUpload({
		url : global.rootPath + "/adv/place/update?type=update",
		fileElementId:"logoFile",
		dataType: 'json',
		
		data : {
			name : encodeURIComponent(name),
			advmentId : advmentId,
			id : id,
			imgUrl : imgUrl,
			playTime : playTime,
			beginTime :beginTime,
			endTime : endTime
		},
		success: function(data,status) {
			//parent.layer.msg(data.msg, 2);
			parent.location.reload();
			var index = parent.layer.getFrameIndex(window.name);
			parent.layer.close(index);
//			if (data.success) {
//				parent.layer.msg(data.msg, 2);
//				refresh();
//    			var index = parent.layer.getFrameIndex(window.name);
//    			parent.layer.close(index);
//    			
//			} else {
//            	parent.layer.msg(data.msg, 2);
//			}
		},
		error:function(data,status,e) {
			//parent.layer.msg(data.msg, 3);
		}
	});
	
}



function cancel(id){
	
	$.layer({
	    shade: [0],
	    area: ['auto','auto'],
	    dialog: {
	        msg: '是否确定下架该广告位？',
	        btns: 2,                    
	        type: 4,
	        btn: ['确定','取消'],
	        yes: function(){
	        	security.ajax({
	        		url : global.rootPath + "/adv/place/cancel",
	        		data : {
	        			id : id
	        		},
	        		beforeSend : function(){
	        			security.showLoading();
	        		},
	        		success : function(code,msg) {
	        			if (msg == "") msg = "下架成功";
	        			security.showSuccess(msg,refresh);
	        		},
	        		error : function(message) {
	        			security.showError(message);
	        		}
	        	});
	        }, no: function(){
	        }
	    }
	});
	
}

function remove(id){
	$.layer({
	    shade: [0],
	    area: ['auto','auto'],
	    dialog: {
	        msg: '是否确定删除该广告位？',
	        btns: 2,                    
	        type: 4,
	        btn: ['确定','取消'],
	        yes: function(){
	        	security.ajax({
	        		url : global.rootPath + "/adv/place/remove",
	        		data : {
	        			id : id
	        		},
	        		beforeSend : function(){
	        			security.showLoading();
	        		},
	        		success : function(code,msg) {
	        			if (msg == "") msg = "删除成功";
	        			security.showSuccess(msg,refresh);
	        		},
	        		error : function(message) {
	        			security.showError(message);
	        		}
	        	});
	        }, no: function(){
	        }
	    }
	});
	
}

function active(id){
	$.layer({
	    shade: [0],
	    area: ['auto','auto'],
	    dialog: {
	        msg: '是否确定上架该广告位？',
	        btns: 2,                    
	        type: 4,
	        btn: ['确定','取消'],
	        yes: function(){
	        	security.ajax({
	        		url : global.rootPath + "/adv/place/active",
	        		data : {
	        			id : id
	        		},
	        		beforeSend : function(){
	        			security.showLoading();
	        		},
	        		success : function(code,msg) {
	        			//if (msg == "") msg = "删除成功";
	        			security.showSuccess(msg,refresh);
	        		},
	        		error : function(message) {
	        			security.showError(message);
	        		}
	        	});
	        }, no: function(){
	        }
	    }
	});
	
}

function closeIframe() {
	var index = parent.layer.getFrameIndex(window.name);
    parent.layer.close(index);
}

function refresh() {
	var formSerialize = $("#form").serializeObject();
	var v = JSON.stringify(formSerialize);
	$("#v").val(encodeURIComponent(v));
	form.submit();
}

/**
 * js本地图片预览，兼容ie[6-9]、火狐、Chrome17+、Opera11+、Maxthon3
 * @param fileObj
 * @param imgPreviewId
 * @param divPreviewId
 * @returns
 */
function previewLocalImage(fileObj, imgPreviewId, divPreviewId) {
	
    var allowExtention = ".jpg,.bmp,.gif,.png"; //允许上传文件的后缀名document.getElementById("hfAllowPicSuffix").value;
    var extention = fileObj.value.substring(fileObj.value.lastIndexOf(".") + 1).toLowerCase();
    var browserVersion = window.navigator.userAgent.toUpperCase();
    
    document.getElementById(divPreviewId).style.display = "inline";
    //本地地址
    $("#imgUrl").val(fileObj.value);
    //判断文件 大小
    var file = fileObj.files[0];
    
    var fileSize = file.size;
    
    var maxSize = 0.5 * 1024 * 1024;
    //文件 大小 不能大于1M
    if (fileSize > parseInt(maxSize)) {
    	security.alert("展示图片最大为512KB，请注意图片大小");
    	document.getElementById(divPreviewId).style.display = "none";
    	$("#imgUrl").val("");
    	return false;
    }
    
    //error msg
    $("#error_img").attr("style","display:none");
    
    
    if (allowExtention.indexOf(extention) > -1) {
        if (fileObj.files) {//HTML5实现预览，兼容chrome、火狐7+等
            if (window.FileReader) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    document.getElementById(imgPreviewId).setAttribute("src", e.target.result);
                }
                reader.readAsDataURL(fileObj.files[0]);
            } else if (browserVersion.indexOf("SAFARI") > -1) {
                alert("不支持Safari6.0以下浏览器的图片预览!");
            }
        } else if (browserVersion.indexOf("MSIE") > -1) {
            if (browserVersion.indexOf("MSIE 6") > -1) {//ie6
                document.getElementById(imgPreviewId).setAttribute("src", fileObj.value);
            } else {//ie[7-9]
                fileObj.select();
                if (browserVersion.indexOf("MSIE 9") > -1)
                    fileObj.blur(); //不加上document.selection.createRange().text在ie9会拒绝访问
                var newPreview = document.getElementById(divPreviewId + "New");
                if (newPreview == null) {
                    newPreview = document.createElement("div");
                    newPreview.setAttribute("id", divPreviewId + "New");
                    newPreview.style.width = document.getElementById(imgPreviewId).width + "px";
                    newPreview.style.height = document.getElementById(imgPreviewId).height + "px";
                    newPreview.style.border = "solid 1px #d2e2e2";
                }
                newPreview.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale',src='" + document.selection.createRange().text + "')";
                var tempDivPreview = document.getElementById(divPreviewId);
                tempDivPreview.style.display = "inline";
                tempDivPreview.parentNode.insertBefore(newPreview, tempDivPreview);
                tempDivPreview.style.display = "none";
            }
        } else if (browserVersion.indexOf("FIREFOX") > -1) {//firefox
            var firefoxVersion = parseFloat(browserVersion.toLowerCase().match(/firefox\/([\d.]+)/)[1]);
            if (firefoxVersion < 7) {//firefox7以下版本
                document.getElementById(imgPreviewId).setAttribute("src", fileObj.files[0].getAsDataURL());
            } else {//firefox7.0+                    
                document.getElementById(imgPreviewId).setAttribute("src", window.URL.createObjectURL(fileObj.files[0]));
            }
        } else {
            document.getElementById(imgPreviewId).setAttribute("src", fileObj.value);
        }
    } else {
        alert("仅支持" + allowExtention + "为后缀名的文件!");
        fileObj.value = ""; //清空选中文件
        if (browserVersion.indexOf("MSIE") > -1) {
            fileObj.select();
            document.selection.clear();
        }
        fileObj.outerHTML = fileObj.outerHTML;
    }
    return fileObj.value;    //返回路径
}